import requests
import json
import pandas as pd
from datetime import datetime, timedelta
import random
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config import EXTERNAL_APIS
from backend.gaode_api import GaodeAPI
from backend.train_api import TrainAPI
from backend.flight_api import FlightAPI

class DataCollector:
    def __init__(self):
        self.supported_cities = [
            '北京', '上海', '广州', '深圳', '南京', '杭州', 
            '成都', '武汉', '西安', '重庆', '天津', '苏州',
            '长沙', '郑州', '青岛', '沈阳', '大连', '厦门'
        ]
        
        # 初始化API客户端
        self.gaode_api = None
        self.train_api = None
        self.flight_api = None
        
        # 检查API配置并初始化
        if EXTERNAL_APIS['GAODE']['ENABLED']:
            self.gaode_api = GaodeAPI(EXTERNAL_APIS['GAODE']['API_KEY'])
        
        if EXTERNAL_APIS['12306']['ENABLED']:
            self.train_api = TrainAPI()
            
        if EXTERNAL_APIS['CTRIP']['ENABLED']:
            self.flight_api = FlightAPI()
        
        # 模拟交通数据（当真实API不可用时使用）
        self.mock_data = self._generate_mock_data()
    
    def _generate_mock_data(self):
        """
        生成模拟交通数据
        """
        mock_data = []
        
        # 高铁数据
        high_speed_routes = [
            ('北京', '上海', 4.5, 553),
            ('北京', '广州', 8.0, 862),
            ('北京', '深圳', 8.5, 936),
            ('上海', '南京', 1.5, 134),
            ('上海', '杭州', 1.0, 73),
            ('广州', '深圳', 0.5, 74),
            ('南京', '杭州', 1.0, 117),
            ('成都', '重庆', 1.5, 154),
            ('武汉', '长沙', 1.5, 164),
            ('西安', '郑州', 2.0, 174)
        ]
        
        for origin, dest, duration, base_price in high_speed_routes:
            # 生成多个班次
            for i in range(3):
                dep_hour = 8 + i * 3
                dep_time = f"{dep_hour:02d}:00"
                arr_time = f"{dep_hour + int(duration):02d}:{int((duration % 1) * 60):02d}"
                
                mock_data.append({
                    'type': 'high_speed_rail',
                    'origin': origin,
                    'destination': dest,
                    'departure_time': dep_time,
                    'arrival_time': arr_time,
                    'price': base_price + random.randint(-50, 50),
                    'duration': duration,
                    'available': True
                })
        
        # 飞机数据
        flight_routes = [
            ('北京', '上海', 2.0, 800),
            ('北京', '广州', 3.0, 1200),
            ('北京', '深圳', 3.5, 1300),
            ('上海', '成都', 3.0, 900),
            ('广州', '成都', 2.5, 800),
            ('深圳', '成都', 2.5, 850),
            ('北京', '西安', 2.0, 600),
            ('上海', '西安', 2.5, 700)
        ]
        
        for origin, dest, duration, base_price in flight_routes:
            for i in range(2):
                dep_hour = 9 + i * 6
                dep_time = f"{dep_hour:02d}:00"
                arr_time = f"{dep_hour + int(duration):02d}:{int((duration % 1) * 60):02d}"
                
                mock_data.append({
                    'type': 'flight',
                    'origin': origin,
                    'destination': dest,
                    'departure_time': dep_time,
                    'arrival_time': arr_time,
                    'price': base_price + random.randint(-200, 200),
                    'duration': duration,
                    'available': True
                })
        
        # 汽车数据（短途）
        bus_routes = [
            ('南京', '苏州', 2.0, 45),
            ('杭州', '苏州', 2.5, 55),
            ('成都', '重庆', 3.5, 80),
            ('武汉', '长沙', 4.0, 90),
            ('西安', '郑州', 5.0, 100)
        ]
        
        for origin, dest, duration, base_price in bus_routes:
            for i in range(2):
                dep_hour = 7 + i * 4
                dep_time = f"{dep_hour:02d}:00"
                arr_time = f"{dep_hour + int(duration):02d}:{int((duration % 1) * 60):02d}"
                
                mock_data.append({
                    'type': 'bus',
                    'origin': origin,
                    'destination': dest,
                    'departure_time': dep_time,
                    'arrival_time': arr_time,
                    'price': base_price + random.randint(-10, 10),
                    'duration': duration,
                    'available': True
                })
        
        return mock_data
    
    def get_transport_data(self, origin, destination, departure_date):
        """
        获取交通数据（优先使用真实API，回退到模拟数据）
        """
        all_routes = []
        
        # 尝试获取真实数据
        if self.gaode_api:
            # 获取公交路线
            transit_routes = self.gaode_api.get_transit_route(origin, destination)
            for route in transit_routes:
                all_routes.append(self._convert_gaode_transit_route(route))
            
            # 获取驾车路线
            driving_routes = self.gaode_api.get_driving_route(origin, destination)
            for route in driving_routes:
                all_routes.append(self._convert_gaode_driving_route(route))
        
        if self.train_api:
            # 获取火车数据
            train_routes = self.train_api.search_trains(origin, destination, departure_date)
            for route in train_routes:
                all_routes.append(self._convert_train_route(route))
        
        if self.flight_api:
            # 获取航班数据
            flight_routes = self.flight_api.search_flights(origin, destination, departure_date)
            for route in flight_routes:
                all_routes.append(self._convert_flight_route(route))
        
        # 如果没有真实数据，使用模拟数据
        if not all_routes:
            for route in self.mock_data:
                if (route['origin'] == origin and route['destination'] == destination) or \
                   (route['origin'] == destination and route['destination'] == origin):
                    all_routes.append(route)
        
        return all_routes
    
    def get_supported_cities(self):
        """
        获取支持的城市列表
        """
        return self.supported_cities
    
    def get_high_speed_rail_data(self, origin, destination, date):
        """
        获取高铁数据（模拟12306 API）
        """
        # 实际实现中应该调用12306 API
        return self._filter_data_by_route('high_speed_rail', origin, destination)
    
    def get_flight_data(self, origin, destination, date):
        """
        获取航班数据（模拟携程/飞猪 API）
        """
        # 实际实现中应该调用航班API
        return self._filter_data_by_route('flight', origin, destination)
    
    def get_bus_data(self, origin, destination, date):
        """
        获取汽车数据
        """
        # 实际实现中应该调用汽车票API
        return self._filter_data_by_route('bus', origin, destination)
    
    def _filter_data_by_route(self, transport_type, origin, destination):
        """
        根据路线筛选数据
        """
        filtered = []
        for route in self.mock_data:
            if (route['type'] == transport_type and 
                route['origin'] == origin and 
                route['destination'] == destination):
                filtered.append(route)
        return filtered
    
    def save_data_to_file(self, filename):
        """
        保存数据到文件
        """
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(self.mock_data, f, ensure_ascii=False, indent=2)
    
    def load_data_from_file(self, filename):
        """
        从文件加载数据
        """
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                self.mock_data = json.load(f)
        except FileNotFoundError:
            print(f"文件 {filename} 不存在，使用默认模拟数据")
    
    def _convert_gaode_transit_route(self, route):
        """
        转换高德公交路线数据格式
        """
        return {
            'type': 'transit',
            'origin': route.get('origin', ''),
            'destination': route.get('destination', ''),
            'departure_time': route.get('departure_time', ''),
            'arrival_time': route.get('arrival_time', ''),
            'price': route.get('cost', 0),
            'duration': route.get('duration', 0) / 60,  # 转换为小时
            'available': True,
            'transfers': route.get('transits', []),
            'distance': route.get('distance', 0)
        }
    
    def _convert_gaode_driving_route(self, route):
        """
        转换高德驾车路线数据格式
        """
        return {
            'type': 'driving',
            'origin': route.get('origin', ''),
            'destination': route.get('destination', ''),
            'departure_time': route.get('departure_time', ''),
            'arrival_time': route.get('arrival_time', ''),
            'price': route.get('toll_cost', 0),
            'duration': route.get('duration', 0) / 60,  # 转换为小时
            'available': True,
            'distance': route.get('distance', 0),
            'traffic_lights': route.get('traffic_lights', 0)
        }
    
    def _convert_train_route(self, route):
        """
        转换火车路线数据格式
        """
        return {
            'type': 'high_speed_rail',
            'origin': route.get('from_station', ''),
            'destination': route.get('to_station', ''),
            'departure_time': route.get('departure_time', ''),
            'arrival_time': route.get('arrival_time', ''),
            'price': route.get('price', {}).get('second', 0),
            'duration': route.get('duration', 0),
            'available': True,
            'train_no': route.get('train_no', ''),
            'train_type': route.get('train_type', ''),
            'seats': route.get('seats', {})
        }
    
    def _convert_flight_route(self, route):
        """
        转换航班路线数据格式
        """
        return {
            'type': 'flight',
            'origin': route.get('from_city', ''),
            'destination': route.get('to_city', ''),
            'departure_time': route.get('departure_time', ''),
            'arrival_time': route.get('arrival_time', ''),
            'price': route.get('price', {}).get('economy', 0),
            'duration': route.get('duration', 0),
            'available': True,
            'flight_no': route.get('flight_no', ''),
            'airline': route.get('airline', ''),
            'aircraft': route.get('aircraft', ''),
            'seats': route.get('seats', {})
        }